// import * as htmlToImage from 'html-to-image';
import { toPng, toJpeg, toBlob, toPixelData, toSvg } from "html-to-image";

export const sleep = (timer: number) => {
    return new Promise<void>(resolve => {
        setTimeout(() => {
            resolve();
        }, timer);
    });
};

export const getURLParams = () => {
    let urlStr = location.search.split("?")[1];
    const urlSearchParams = new URLSearchParams(urlStr);
    const result = Object.fromEntries(urlSearchParams.entries());
    return result;
};

export const maskEmail = (email: string) => {
    const atIndex = email.indexOf("@");
    if (atIndex > 0) {
        const prefix = email.slice(0, atIndex);
        const maskedPrefix = prefix.slice(0, 3) + "***";
        const domain = email.slice(atIndex);
        return maskedPrefix + domain;
    }
    return email;
};

export const sortList = (list: any[], key: string, isDown = true) => {
    list.sort((a: any, b: any) => {
        const comparison = a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
        return isDown ? -comparison : comparison;
    });
};

export const checkSort = (list: any[], key: string, isDown = true) => {
    let suc = [];
    let err = [];
    for (let i = 1; i < list.length; i++) {
        let num = list[i][key] - list[i - 1][key];
        if (num >= 0) {
            if (isDown) {
                suc.push(i)
            }
            else {
                err.push(i)
            }
        }
    }
    if (err.length) {
        console.log("检查失败", err);
        return false;
    }
    return true;
}

export const isHash = (str: string) => {
    return str.toLowerCase().startsWith("0x");
};

export const maskHash = (str: string, total = 6) => {
    if (isHash(str)) {
        return str.slice(0, total) + "***";
    }
    return str;
};

// for (var i = 0; i < 10; i++) {
//     test();
// }

// function test() {
//     let isDown = Math.random() > 0.5;
//     console.log("isDown ------------- ", isDown);
//     let ary = [];
//     for (var i = 0; i < 10; i++) {
//         ary.push({ a: Math.floor(Math.random() * 100) });
//     }
//     sortList1(ary, "a", isDown);
//     console.log(ary.map(i => i.a));
// }

export const domToImage = (dom: any) => {
    toPng(dom).then(dataUrl => {
        var link = document.createElement("a");
        link.download = "share.png";
        link.href = dataUrl;
        link.click();
    });
};

export function debounce(func: (...args: any[]) => void, delay = 900): (...args: any[]) => void {
    let timeoutId: any;

    return function (...args) {
        clearTimeout(timeoutId);
        console.log("触发防抖")
        timeoutId = setTimeout(() => {
            func(...args);
        }, delay);
    };
}

export function getVarStyle(key: string) {
    const root = getComputedStyle(document.documentElement).getPropertyValue(key);
    console.log(root);
    return root;
}


export function shareTwitter(title: string, recommend: string) {
    title = title || "本文内容由@chainingview提供，更多信息请关注@chainingview（ 致力于区块链生态服务）";
    recommend = recommend || "";
    let url;
    if (recommend) {
        url = `https://twitter.com/intent/tweet?text=${title}&url=https://alpha.chainingview.io/reward/recommend/${recommend}&hashtags=ChainingView`;
    }
    else {
        url = `https://twitter.com/intent/tweet?text=${title}&url=https://alpha.chainingview.io&hashtags=ChainingView`;
    }
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const w = 600;
    const h = 500;
    const left = (windowWidth - w) / 2;
    const top = (windowHeight - h) / 2;
    window.open(url, "newWindow", `width=${w},height=${h},left=${left},top=${top}`);

}


export function getFixNum(n: number) {
    if (!n) return 0;
    let ary = n.toString().split(".");
    if (ary.length == 2) {
        return ary[1].length;
    }
    return 0;
}